#!/usr/bin/env python
import pygtk, os, sys, gtk, gobject, webbrowser, re, httplib, xml.dom.minidom, time
pygtk.require('2.0')
APP_DIR = os.path.dirname(os.path.abspath(__file__))+'/'

class loginWindow:
    loginCallback = object

    def __init__(self, cb):
        self.loginCallback = cb

        print "Open window..."
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_size_request(250, 150)
        self.window.set_border_width(10)
        self.window.set_title("Login into Google Account")
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_modal(True)

        # Load the login entry box
        userLabel = gtk.Label("Username: ")
        userLabel.show()

        userEntry = gtk.Entry()
        userEntry.set_max_length(50)
        userEntry.set_text('')
        userEntry.connect("activate", lambda w: self._loginCallback(userEntry.get_text(),passEntry.get_text()))
        userEntry.grab_focus()
        userEntry.show()

        userBox = gtk.HBox(False, 0)
        userBox.pack_start(userLabel, False, False, 0)
        userBox.pack_start(userEntry, False, False, 0)
        userBox.show()

        # Load the pass entry box
        passLabel = gtk.Label("Password: ")
        passLabel.show()

        passEntry = gtk.Entry()
        passEntry.set_max_length(50)
        passEntry.set_text('')
        passEntry.connect("activate", lambda w: self._loginCallback(userEntry.get_text(),passEntry.get_text()))
        passEntry.set_visibility(False)
        passEntry.show()

        passBox = gtk.HBox(False, 0)
        passBox.pack_start(passLabel, False, False, 0)
        passBox.pack_start(passEntry, False, False, 0)
        passBox.show()

        # Append login and pass entry box to vbox
        vbox = gtk.VBox(False, 0)
        vbox.pack_start(userBox, True, True, 0)
        vbox.pack_start(passBox, True, True, 0)
        self.window.add(vbox)

        okButton = gtk.Button(stock=gtk.STOCK_OK)
        okButton.connect("clicked", lambda w: self._loginCallback(userEntry.get_text(),passEntry.get_text()))
        okButton.set_flags(gtk.CAN_DEFAULT)
        okButton.show()
        okButton.set_size_request(10, 20)

        cancelButton = gtk.Button(stock=gtk.STOCK_CANCEL)
        cancelButton.connect("clicked", lambda w: gtk.main_quit())
        cancelButton.show()
        cancelButton.set_size_request(10, 20)

        hbox = gtk.HBox(False, 0)
        hbox.set_border_width(5)
        hbox.pack_start(cancelButton, True, True, 0)
        hbox.pack_start(okButton, True, True, 0)
        vbox.add(hbox)

        okButton.grab_default()

        hbox.show()
        vbox.show()

    def run(self):
        self.window.show()
        return None

    def _loginCallback(self, user, passwd):
        self.window.hide()
        gtk.gdk.flush()
        #main.lManager.loginIntoModules(user,passwd)
        self.loginCallback(user,passwd)


class googleFeedManager:
   feedUri = ''
   serviceId = ''
   token = ''
   feed = ''

   testing = False
   testFeed = 'gcal.xml'#'test.xml'

   redirects_remaining = 4   
   
   def __init__(self, serviceId, feedUri):
       self.serviceId = serviceId
       self.feedUri = feedUri

   def getAuthToken(self, user, passwd):
       self.token = ''

       print "Authenticating..."
       if (self.testing):       
         self.token = '1'
         return 200
       
      
       h = httplib.HTTPSConnection('www.google.com')
       auth_uri = '/accounts/ClientLogin'
       headers = {'Content-Type': 'application/x-www-form-urlencoded'}
       myrequest = "Email="+user+"&Passwd="+passwd+"&service="+self.serviceId+"&source=gNotifier&accountType=HOSTED_OR_GOOGLE"

       try:
        conn = h.request('POST', auth_uri, body=myrequest, headers=headers)
       except Exception, e:
        raise
       try:
        res = h.getresponse()
        print res.status, res.reason
        if (res.status == 200):
          content = res.read()
          self.token = re.search('Auth=(\S*)', content).group(1)
          self.SID = re.search('SID=(\S*)', content).group(1)
          self.LSID = re.search('LSID=(\S*)', content).group(1)
       except Exception, e:
        raise

       print 'SID: '+self.SID
       print 'LSID: '+self.LSID
       return res.status

   def getFeed(self):
        self.feed = ''

        if (self.testing):       
         f=open(self.testFeed, 'r')
         self.feed = f.read()
         return 200

        print "getGmail...";   
        h = httplib.HTTPSConnection('www.google.com')
        if (self.serviceId == 'mail'):
            auth_uri = self.feedUri+'?auth='+self.token
        elif (self.serviceId == 'reader'):
            auth_uri = self.feedUri+'?SID='+self.SID
        else:
            auth_uri = self.feedUri
        headers = {'Content-Type': 'application/atom+xml', 'Authorization': 'GoogleLogin auth=%s' % self.token}
        print 'Entering '+auth_uri
        try:
            #conn = h.request('POST', auth_uri, body=body, headers=headers)
            h.putrequest('GET', auth_uri)
            for key in headers:        
                h.putheader(key, headers[key])
            h.endheaders()
        except Exception, e:
            raise
        try:
            res = h.getresponse()       
            print res.status, res.reason
            if (res.status == 200):
                self.feed = res.read()
            elif (res.status == 302):
                self.feedUri = res.getheader('Location')
                #print res.read()
                #print self.feedUri
                self.redirects_remaining = self.redirects_remaining - 1
                if (self.redirects_remaining > 0):            
                    return self.getFeed()
            else:
                print 'Error'
                print res.read()
        except Exception, e:
            raise
        
        return res.status

class loginManager:
    user = ''
    passwd = ''
    g = {}

    def __init__(self,g):
        self.g = g
    
    def checkUserPass(self):
        if (self.user == '' or self.passwd == ''):
            loginwindow = loginWindow(self.loginIntoModules)
            loginwindow.run()

    def loginIntoModules(self, user, passwd):
        self.user = user
        self.passwd = passwd
        for k in self.g:
            self.g[k].loginInto(self.user, self.passwd)

